import {useParams} from "react-router-dom";
import Header from "../../components/Header/Header.tsx";
import {Avatar, Button, Card, Input, message, Space, Tooltip} from "antd";
import Player from "xgplayer";
import {useEffect, useRef, useState} from "react";
//import "./index.ts"
import "./index.css"
import "../../../node_modules/xgplayer/dist/index.min.css";
import {Monitor, MonitorOff, Voice, VoiceOff} from "@icon-park/react";
import {CaretLeftOutlined, CaretRightOutlined, SendOutlined, SmileOutlined,} from "@ant-design/icons";
import {getRoomInfoUsingGet} from "../../api/roomController.ts";
import {joinRoom} from "./index.ts";
import {useSelector} from "react-redux";
import {RootState} from "../../store";
import RoomInfoVO = API.RoomInfoVO;
import BaseResponseBoolean_ = API.BaseResponseBoolean_;


const RoomInfo = () => {
    const { ids } = useParams<{ ids: string }>();
    const [roomInfo, setRoomInfo] = useState<RoomInfoVO | null>(null);
    const [chatWidth,setChatWidth] = useState("300px");
    const [openChat,setOpenChat] = useState(true);
    const [player, setPlayer] = useState(null); // 用于保存播放器实例
    const FriendPlayerContainer = useRef(null);

    const [openAudio, setOpenAudio] = useState(true);
    const [openVideo, setOpenVideo] = useState(true);
    const [openShare, setOpenShare] = useState(true);
    const [openScreenRecording, setOpenScreenRecording] = useState(true);
    const [openSign, setOpenSign] = useState(true);
    const [whiteboard, setWhiteboard] = useState(true);

    //获取登录用户
    const userInfo = useSelector((state: RootState) => state.loginUser);


    const stopTracks = (stream) => {
        if (stream) {
            stream.getTracks().forEach(track => track.stop()); // 停止所有轨道
        }
    };
    const initializePlayer = () => {
        if (player) {
            stopTracks(player.video?.srcObject); // 停止轨道
            player.destroy();
        }

        // 初始化 xgplaye
        const newPlayer = new Player({
            id: "playerContainer",
            url: "",
            ignores: ["time", "progress"], // 隐藏播放按钮和其他控件
            autoplay: true, // 自动播放
        });

        // 等待播放器准备完成
        newPlayer.once("ready", () => {
            navigator.mediaDevices
                .getUserMedia({ video: !openVideo, audio: !openAudio })
                .then((stream) => {
                    newPlayer.video.srcObject = stream; // 将媒体流绑定到视频
                    // startCall(stream,FriendPlayerContainer.current)
                    newPlayer.video.play();
                }).catch((error) => {
                const errorNote = document.querySelector('.xgplayer-errornote');
                if (errorNote) {
                    // 修改为带有链接的提示信息，点击刷新权限
                    errorNote.innerHTML =
                        `您可能还未开启权限，请开启权限
                <a href="#" onclick="window.location.reload(); return false;" style="color: darkred; text-decoration: underline;">
                    点击重新获取权限
                    </a>
                `
                }
            });
        });

        // 监听播放器的 error 事件
        newPlayer.on("error", () => {
            const errorNote = document.querySelector('.xgplayer-errornote');
            if (errorNote) {
                errorNote.innerHTML = `
                您可能还未开启权限，请开启权限
                <a href="#" onclick="window.location.reload(); return false;" style="color: darkred; text-decoration: underline;">
                    点击重新获取权限
                </a>
            `;
            }
        });
        setPlayer(newPlayer);
    }

    //开启共享函数
    const initShareStream = ()=>{

        // 如果存在旧的 player 和流，先销毁旧的流和 player
        if (player) {
            const oldStream = player.video?.srcObject;
            if (oldStream) {
                const tracks = oldStream.getTracks();
                tracks.forEach((track) => track.stop()); // 停止所有轨道
            }
            player.destroy(); // 销毁旧的播放器
        }

        // 初始化 xgplaye
        const newPlayer = new Player({
            id: "playerContainer",
            url: "",
            ignores: ["time", "progress"], // 隐藏播放按钮和其他控件
            autoplay: true, // 自动播放
        });

        // 等待播放器准备完成
        newPlayer.once("ready", () => {
              if(!openShare){
                  // 如果打开视频权限，获取屏幕共享流
                  navigator.mediaDevices
                      .getDisplayMedia({ video: true, audio: true }) // 获取屏幕共享流
                      .then((stream) => {
                          newPlayer.video.srcObject = stream; // 将媒体流绑定到视频
                          newPlayer.video.play();
                          if(stream.getVideoTracks()[0] != null ){
                              console.log(stream.getVideoTracks())
                          }
                          const videoTrack = stream.getVideoTracks()[0]
                          videoTrack.onended = () =>{
                              setOpenShare(true)
                          }
                      }).catch((error) => {
                      setOpenShare(true)
                  });
              }
        });
        newPlayer.on("error", () => {
            const errorNote = document.querySelector('.xgplayer-errornote');
            if (errorNote) {
                errorNote.innerHTML = `
                您可能还未开启权限，请开启权限
                <a href="#" onclick="window.location.reload(); return false;" style="color: darkred; text-decoration: underline;">
                    点击重新获取权限
                </a>
            `;
            }
        });
        setPlayer(newPlayer);
    }

    //点击开启视频按钮
    useEffect(() => {
       // 初始化播放器
        initializePlayer();
        return () => {
            if (player) {
                stopTracks(player.video?.srcObject); // 确保停止轨道
                player.destroy();
            }
        };
    }, [openAudio,openVideo]);

    useEffect(() => {
        // 初始化播放器
        initShareStream();
        // 销毁播放器
        return () => {
            if (player) {
                player.destroy();  // 销毁播放器
            }
        };
    }, [openShare]);


    // 定义操作函数
    const openAudioStream = () => {
        setOpenAudio(true);
    }
    const closeAudioStream = () => {
        setOpenAudio(false);
    }

    const openVideoStream = () => {
        setOpenVideo(true);
    }
    const closeVideoStream = () => {
        setOpenVideo(false);
    }

    const openShareStream = () => {
        setOpenShare(true);
        initShareStream()
    }
    const closeShareStream = () => {
        setOpenShare(false);
        initializePlayer()
    }

    const openScreenRecordingStream = () => {
        setOpenScreenRecording(true);
    }
    const closeScreenRecordingStream = () => {
        setOpenScreenRecording(false);
    }

    const openSignStream = () => {
        setOpenSign(true);
    }
    const closeSignStream = () => {
        setOpenSign(false);
    }

    const openWhiteboardStream = () => {
        setWhiteboard(true);
    }
    const closeWhiteboardStream = () => {
        setWhiteboard(false);
    }

    //获取房间信息
    const getRoomInfo = async () => {
        try {
            const res: BaseResponseBoolean_ = await getRoomInfoUsingGet({ roomId: ids });
            setRoomInfo(res.data); // 确保数据设置到状态中
        } catch (e: any) {
            message.error(e.message); // 添加 `any` 类型以避免类型错误
        }
    };

    useEffect(() => {
        getRoomInfo();
        joinRoom(ids,userInfo.id);
    }, []);

  return (
    <div>
      <Header />
      <Card title={"房间 " + roomInfo?.roomName + " 信息"} className="shadow">
        {/* 根容器 */}
        <div className="flex flex-col xl:flex-row">
          {/* 左侧区域 */}
            <div
                className={`flex flex-col ${openChat ? "xl:w-4/5" : "xl:w-[99%]"} xl:pr-4 transition-all duration-500`}
            >

                {/* 视频容器 */}
                <div
                    id="playerContainer"
                    className="w-full relative bg-black"
                    style={{
                        paddingTop: "56.25%", // 16:9 比例
                    }}
                ></div>
                <h1>123123</h1>
                <div className="relative w-full" style={{paddingTop: '56.25%'}}>
                    <video
                        ref={FriendPlayerContainer}
                        controls={true}
                        className="absolute top-0 left-0 w-full h-full bg-black"
                    ></video>
                </div>
                {/* 按钮容器 */}
                <div className="mt-4 flex justify-center xl:justify-center">
                    <Space wrap>
                        {
                            openAudio ? (<Tooltip placement="bottom" title={"打开麦克风"}>
                                <Button
                                    type="primary"
                                    shape="circle"
                                    size="large"
                                    title="打开麦克风"
                                    onClick={() => {
                                        closeAudioStream()
                                    }}
                                    icon={<Voice theme="outline" size="24" fill="#fff"/>}
                                />
                            </Tooltip>) : <Tooltip placement="bottom" title={"关闭麦克风"}>
                                <Button
                                    type="primary"
                                    shape="circle"
                                    size={"large"}
                                    title={"关闭麦克风"}
                                    onClick={() => {
                                        openAudioStream()
                                    }}
                                    icon={<VoiceOff theme="outline" size="24" fill="#e54538"/>}
                                />
                            </Tooltip>
                        }
                        {
                            openVideo ? (
                                <Tooltip placement="bottom" title={"打开视频"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        onClick={() => {
                                            closeVideoStream()
                                        }}
                                        icon={<Monitor theme="outline" size="24" fill="#fff"/>}
                                    />
                                </Tooltip>
                            ) : (
                                <Tooltip placement="bottom" title={"关闭视频"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        onClick={() => {
                                            openVideoStream()
                                        }}
                                        icon={
                                            <MonitorOff theme="outline" size="24" fill="#e54538"/>
                                        }
                                    ></Button>
                                </Tooltip>
                            )
                        }
                        {
                            openShare ? (
                                <Tooltip placement="bottom" title={"共享屏幕"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        icon={
                                            <i
                                                className={"iconfont icon-gongxiangpingmu text-2xl"}
                                            ></i>
                                        }
                                        onClick={() => {
                                            closeShareStream();
                                        }}
                                    ></Button>
                                </Tooltip>
                            ) : (
                                <Tooltip placement="bottom" title={"关闭共享"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        icon={
                                            <i
                                                className={
                                                    "iconfont icon-guanbigongxiangpingmu text-2xl text-red-500"
                                                }
                                            ></i>
                                        }
                                        onClick={() => {
                                            openShareStream();
                                        }}
                                    ></Button>
                                </Tooltip>
                            )
                        }
                        {
                            openScreenRecording ? (
                                <Tooltip placement="bottom" title={"录制屏幕"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        icon={
                                            <i
                                                className={
                                                    "iconfont icon-luzhi text-3xl text-white-500"
                                                }
                                            ></i>
                                        }
                                        onClick={() => {
                                            closeScreenRecordingStream(); // 打开麦克风逻辑
                                        }}
                                    ></Button>
                                </Tooltip>
                            ) : (
                                <Tooltip placement="bottom" title={"关闭录制"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        icon={
                                            <i
                                                className={
                                                    "iconfont icon-stop-circle-line text-3xl text-red-500"
                                                }
                                            ></i>
                                        }
                                        onClick={() => {
                                            openScreenRecordingStream(); // 打开麦克风逻辑
                                        }}
                                    ></Button>
                                </Tooltip>
                            )
                        }
                        {
                            openSign ? (
                                <Tooltip placement="bottom" title={"签到"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        icon={
                                            <i
                                                className={
                                                    "iconfont icon-qiandao text-2xl text-white-500"
                                                }
                                            ></i>
                                        }
                                        onClick={() => {
                                            closeSignStream()
                                        }}
                                    ></Button>
                                </Tooltip>
                            ) : (
                                <Tooltip placement="bottom" title={"签到"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        icon={
                                            <i
                                                className={
                                                    "iconfont icon-qiandao text-2xl text-red-500"
                                                }
                                            ></i>

                                        }
                                        onClick={() => {
                                            openSignStream()
                                        }}
                                    ></Button>
                                </Tooltip>
                            )
                        }
                        {
                            whiteboard ? (
                                <Tooltip placement="bottom" title={"共享白板"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        icon={
                                            <i
                                                className={
                                                    "iconfont icon-blackboard text-2xl text-white-500"
                                                }
                                            ></i>
                                        }
                                        onClick={() => {
                                            closeWhiteboardStream()
                                        }}
                                    ></Button>
                                </Tooltip>
                            ) : (
                                <Tooltip placement="bottom" title={"共享白板"}>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        size={"large"}
                                        icon={
                                            <i
                                                className={
                                                    "iconfont icon-blackboard text-2xl text-red-500"
                                                }
                                            ></i>
                                        }
                                        onClick={() => {
                                            openWhiteboardStream()
                                        }}
                                    ></Button>
                                </Tooltip>
                            )
                        }
                    </Space>
                </div>
            </div>

            {/* 右侧 Card 区域 */}
            <Card
                title={"房间 " + roomInfo?.roomName}
                className="shadow mt-4 xl:mt-0"
                style={{
                    flex: chatWidth === "300px" ? "1" : "0",  // 根据 chatWidth 来设置 flex
                    minWidth: chatWidth,
                    overflowY: openChat ? "scroll" : "hidden", // 根据 openChat 来控制是否显示滚动条
                    overflowX: openChat ? "scroll" : "hidden", // 根据 openChat 来控制是否显示滚动条
                    maxHeight: "calc(100vh - 80px)",
                    position: "relative", // 使子元素可以使用绝对定位
                }}
          >
              <div className={""}>
                  <div className={"absolute top-150 left-0 hidden xl:block"}>
                      <div
                          className={
                              "cursor-pointer text-2xl w-5 h-10 flex items-center justify-center rounded-full bg-clip-border border-2 border-black transition-all duration-300 hover:border-blue-500"
                          }
                          onClick={() => {
                              setOpenChat(!openChat); // 切换 openChat 状态
                              setChatWidth(openChat ? "22px" : "300px"); // 控制聊天区域宽度
                          }}
                      >
                          {/* 根据 openChat 的值来控制显示和隐藏 */}
                          {openChat ? (
                              <CaretRightOutlined
                                  className={"absolute text-gray-400"}
                                  style={{left: "0.01px"}}
                              />
                          ) : (
                              <CaretLeftOutlined
                                  className={"absolute text-gray-400"}
                                  style={{left: "-3px"}}
                              />
                          )}
                      </div>
              </div>
              {/* 处理聊天区域 */}
              <div className={"Comments-left mt-2 flex items-center"}>
                  <Avatar
                      size={50}
                      src={
                          "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
                      }
                  ></Avatar>
                  <div className={"ml-3"} style={{width: "calc(100% - 70px)"}}>
                      <div
                          className="bg-gray-200 p-3 rounded-lg break-words whitespace-pre-wrap"
                          style={{width: "100%"}}
                      >
                          3123123123213123123132123121321231231323123123121321323123132132123132123132132123312132231123132132132132312312132312132132123132132312321123312132
                      </div>
                  </div>
              </div>
              {Array.from({length: 10}).map((_, index) => (
                  <div
                      key={index}
                  className="Comments-left mt-3 flex items-center"
                >
                  <div className="mr-3" style={{ width: "calc(100% - 70px)" }}>
                    <div
                      className="bg-gray-200 p-3 rounded-lg break-words whitespace-pre-wrap"
                      style={{ width: "100%" }}
                    >
                      3123123123213123123132123121321231231323123123121321323123132132123132123132132123312132231123132132132132312312132312132132123132132312321123312132
                    </div>
                  </div>
                  <Avatar
                    size={50}
                    src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
                  />
                </div>
              ))}
                {/* 固定在底部的输入框区域 */}
                <div
                    style={{
                        position: "sticky", // 使用sticky定位
                        bottom: 0, // 始终贴合底部
                        left: 0,
                        right: 0,
                        background: "white", // 确保输入框在内容上方
                        zIndex: 10, // 确保输入框显示在内容上层
                    }}
                    className={"pt-2 pb-2"}
                >
                    <Input
                        className="flex-1 p-2 border-2 border-gray-300 rounded-l-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
                        placeholder="请输入内容..."
                        suffix={
                            <div className="flex space-x-3">
                                <Button
                                    icon={<SmileOutlined />}
                                    className="w-8 h-8 bg-green-500 text-white rounded-full flex items-center justify-center hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-300"
                                />
                                {/* 发送按钮 */}
                                <Button
                                    icon={<SendOutlined />}
                                    className="w-8 h-8 bg-blue-500 text-white rounded-full flex items-center justify-center hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-300"
                                />
                            </div>
                        }
                    />
                </div>
            </div>
          </Card>
        </div>
      </Card>
    </div>
  );
};

export default RoomInfo;
